package com.atguigu.gmall.cart.controller;

import com.atguigu.gmall.cart.intercepter.LoginIntercepter;
import com.atguigu.gmall.cart.pojo.Cart;
import com.atguigu.gmall.cart.pojo.UserInfo;
import com.atguigu.gmall.cart.service.CartService;
import com.atguigu.gmall.common.bean.ResponseVo;
import com.atguigu.gmall.common.exception.CartException;
import com.sun.org.apache.xml.internal.resolver.CatalogException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.stereotype.Service;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.*;

import java.util.List;

@Controller
public class CartController {

    @Autowired
    CartService cartService;

    /**
     * 更改cart中sku的选中状态
     * @param skuId
     * @param check
     * @return
     */
    @PostMapping("updateStatus")
    @ResponseBody
    public ResponseVo updateStatus(@RequestBody Cart cart){
        this.cartService.updateStatus(cart);
        return ResponseVo.ok();
    }


    @GetMapping("cartInfo/{userId}")
    @ResponseBody
    public ResponseVo<List<Cart>> getCartInfoByUserId(@PathVariable Long userId){
        List<Cart> carts =   this.cartService.getCartInfoByUserId(userId);
        return ResponseVo.ok(carts);
    }

    /**
     * 添加购物车
     * @return
     */
    @GetMapping
    public String cart(Cart cart){
        //非空判断
        if (cart==null||cart.getSkuId()==null){
            throw new CartException("没有选择到购物车信息的商品");
        }
        this.cartService.addCart(cart);
        //因为添加购物车需要查询购物车的相关信息，所以需要skuId
        return "redirect:http://cart.gmall.com/addCart?skuId="+cart.getSkuId();
    }
    //通过skuId查询购物车的相关信息
    @GetMapping("addCart")
    public String addCart(@RequestParam("skuId") Long skuId, Model model){
       Cart cart =  this.cartService.queryCartBySkuId(skuId);
       model.addAttribute("cart",cart);
        return "addCart";
    }

    //不需要任何数据直接查询购物车列表
    @GetMapping("cart.html")
    public String queryCarts(Model model){
      List<Cart> carts =   this.cartService.queryCarts();
      model.addAttribute("carts",carts);
      return "cart";
    }

    //根据skuId删除购物车中的对应的sku
    @PostMapping("deleteCart")
    @ResponseBody
    public ResponseVo deleteBySkuId(@RequestParam Long skuId){
        this.cartService.deleteBySkuId(skuId);
        return ResponseVo.ok();
    }
    //更新sku的相关信息
    @PostMapping("updateNum")
    @ResponseBody
    public ResponseVo updateNum(@RequestBody Cart cart){
        this.cartService.updateNum(cart);
        return ResponseVo.ok();
    }


}
